package com.jxdinfo.hussar.cloud.module.example.lift.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jxdinfo.hussar.cloud.module.example.lift.dao.LiftDao;
import com.jxdinfo.hussar.cloud.module.example.lift.dao.LiftDataDao;
import com.jxdinfo.hussar.cloud.module.example.lift.dao.LiftNoticeDao;
import com.jxdinfo.hussar.cloud.module.example.lift.dto.LiftDeviceInfoDto;
import com.jxdinfo.hussar.cloud.module.example.lift.dto.LiftDto;
import com.jxdinfo.hussar.cloud.module.example.lift.dto.LiftSearchDto;
import com.jxdinfo.hussar.cloud.module.example.lift.dto.LiftTodayRealDataDto;
import com.jxdinfo.hussar.cloud.module.example.lift.model.Lift;
import com.jxdinfo.hussar.cloud.module.example.lift.model.LiftData;
import com.jxdinfo.hussar.cloud.module.example.lift.service.LiftService;
import com.jxdinfo.hussar.platform.core.base.apiresult.ApiResponse;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * 升降机表(Lift)表服务实现类
 *
 * @author makejava
 * @since 2023-10-23 17:34:01
 */
@Service("liftService")
public class LiftServiceImpl extends ServiceImpl<LiftDao, Lift> implements LiftService {
    @Resource
    private LiftDao liftDao;
    @Resource
    private LiftDataDao liftDataDao;
    @Resource
    private LiftNoticeDao liftNoticeDao;
    @Override
    public List<Lift> findList(LiftSearchDto liftSearchDto) {
        LambdaQueryWrapper<Lift> wrapper = new LambdaQueryWrapper();
        wrapper.eq(StrUtil.isNotBlank(liftSearchDto.getId()),Lift::getId,liftSearchDto.getId())
                .eq(StrUtil.isNotBlank(liftSearchDto.getTyProjectCode()),Lift::getTyProjectCode,liftSearchDto.getTyProjectCode())
                .eq(Lift::getTyDeleteStatus,0);
        List list = liftDao.selectList(wrapper);
        return list;
    }

    @Override
    public Map<String, Integer> findLiftAlarmCount(LiftSearchDto liftSearchDto) {
        Map<String, Integer> alarmMap = new HashMap<>();
        LambdaQueryWrapper<Lift> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ObjectUtils.isNotEmpty(liftSearchDto.getTyProjectCode()),Lift::getTyProjectCode,liftSearchDto.getTyProjectCode())
                .eq(Lift::getTyDeleteStatus,0)
                .orderByDesc(Lift::getTyCreateTime);
        List<Lift> liftList = liftDao.selectList(wrapper);

        List<LiftDeviceInfoDto> liftOnLineDeviceList = new ArrayList<>();
        //List<LiftDeviceInfoDto> liftAllDeviceList = new ArrayList<>();

        if(ObjectUtils.isNotEmpty(liftList)){
//            Map<String, DeviceInfoDto> deviceInfoDtoMap = deviceService.findDeviceAndLocationByProductType(DeviceTypeEnum.DEVICE_TYPE_TOWER, liftSearchDto.getTyProjectCode());
//            for(Lift lift : liftList){
//                DeviceInfoDto liftDeviceInfoDto = deviceInfoDtoMap.get(lift.getDeviceCode());
//                if(liftDeviceInfoDto != null){
//                    if(liftDeviceInfoDto.getOnlineStatus()==1){
//                        LiftDeviceInfoDto liftDeviceInfo = new LiftDeviceInfoDto();
//                        liftDeviceInfo.setDeviceCode(liftDeviceInfoDto.getDeviceCode());
//                        liftDeviceInfo.setDeviceStatus(liftDeviceInfoDto.getOnlineStatus());
//                        liftOnLineDeviceList.add(liftDeviceInfo);
//                    }
//                }
//            }
        }

        //获取在线设备数量
        //Integer inLineDeviceCount = dao.getLiftCount(liftSearchDto.getTyProjectCode(), 0);

        //获取所有设备数量
        //Integer allDeviceCount = dao.getAllLiftCount(liftSearchDto.getTyProjectCode());

        //获取预警数量
        //Integer warnCount = liftDataAlarmDao.getLiftAlarmsCount(liftSearchDto.getTyProjectCode(), 1);
        Integer warnCount = liftNoticeDao.getDayLiftNoticeCount(liftSearchDto.getTyProjectCode(), 1);

        //获取报警数量
        //Integer alarmCount = liftDataAlarmDao.getLiftAlarmsCount(liftSearchDto.getTyProjectCode(), 2);
        Integer alarmCount = liftNoticeDao.getDayLiftNoticeCount(liftSearchDto.getTyProjectCode(), 2);

        alarmMap.put("inLineDeviceCount",liftOnLineDeviceList.size());
        alarmMap.put("allDeviceCount",liftList.size());
        alarmMap.put("warnCount",warnCount);
        alarmMap.put("alarmCount",alarmCount);
        return alarmMap;
    }

    @Override
    public LiftTodayRealDataDto findLiftRealData(String liftId, String tyProjectCode) {
        LiftTodayRealDataDto liftTodayRealDataDto = new  LiftTodayRealDataDto();

        Lift lift = liftDao.getLift(liftId, tyProjectCode);

        if(ObjectUtils.isNotEmpty(lift)){
            LambdaQueryWrapper<LiftData> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(LiftData::getLiftId,liftId).eq(LiftData::getTyProjectCode,tyProjectCode);
            List<LiftData> liftDataList = liftDataDao.selectList(wrapper);
            liftTodayRealDataDto.setWorkStatus(lift.getWorkStatus());
            liftTodayRealDataDto.setTodayWorkNum(lift.getTodayWorkNum());
            liftTodayRealDataDto.setTodayWorkWeight(BigDecimal.valueOf(lift.getTodayWorkWeight()));
            liftTodayRealDataDto.setTodayWorkDuration(lift.getTodayWorkDuration());
            liftTodayRealDataDto.setLiftCockpitImg(lift.getLiftCockpitImg());
            liftTodayRealDataDto.setCliverCockpitImg(lift.getCliverCockpitImg());
            if(ObjectUtils.isNotEmpty(liftDataList)){
                for(LiftData liftData :liftDataList){
                    if(ObjectUtils.isNotEmpty(liftData.getDataType())){
                        if(liftData.getDataType()==1){
                            liftTodayRealDataDto.setWeight(liftData.getMeasureValue().toString());
                        }
                        if(liftData.getDataType()==2){
                            liftTodayRealDataDto.setSpeed(liftData.getMeasureValue().toString());
                        }
                        if(liftData.getDataType()==3){
                            liftTodayRealDataDto.setHeight(liftData.getMeasureValue().toString());
                        }
                        if(liftData.getDataType()==4){
                            liftTodayRealDataDto.setObliquityX(liftData.getMeasureValue().toString());
                        }
                        if(liftData.getDataType()==5){
                            liftTodayRealDataDto.setObliquityY(liftData.getMeasureValue().toString());
                        }
                        if(liftData.getDataType()==6){
                            liftTodayRealDataDto.setWind(liftData.getMeasureValue().toString());
                        }
                        if(liftData.getDataType()==7){
                            liftTodayRealDataDto.setPeoples(String.valueOf(liftData.getMeasureValue().intValue()));
                        }
                        if(liftData.getDataType()==8){
                            liftTodayRealDataDto.setFloor(String.valueOf(liftData.getMeasureValue().intValue()));
                        }
                    }
                }
            }
        }
        return liftTodayRealDataDto;
    }

    /**
     * 分页查询升降机列表
     * @param liftSearchDto
     * @return
     */
    @Override
    public Page<Lift> findPage(LiftSearchDto liftSearchDto) {
        LambdaQueryWrapper<Lift> wrapper = new LambdaQueryWrapper();
        wrapper.eq(StrUtil.isNotBlank(liftSearchDto.getId()),Lift::getId,liftSearchDto.getId())
                .eq(StrUtil.isNotBlank(liftSearchDto.getTyProjectCode()),Lift::getTyProjectCode,liftSearchDto.getTyProjectCode())
                .eq(Lift::getTyDeleteStatus,0)
                .orderByDesc(Lift::getTyCreateTime);
        Page<Lift> page = new Page<>(liftSearchDto.getPage(),liftSearchDto.getRows());
        Page<Lift> pageResult = liftDao.selectPage(page,wrapper);
        return pageResult;
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ApiResponse insert(LiftDto liftDto) {
        //查询升降机是否已存在
        LambdaQueryWrapper<Lift> wrapper = new LambdaQueryWrapper();
        wrapper.eq(ObjectUtils.isNotEmpty(liftDto.getLiftName()),Lift::getLiftName,liftDto.getLiftName())
                .eq(ObjectUtils.isNotEmpty(liftDto.getTyProjectCode()),Lift::getTyProjectCode,liftDto.getTyProjectCode())
                .eq(Lift::getTyDeleteStatus,0);
        List<Lift> lifts = liftDao.selectList(wrapper);
        if(lifts.size()>0){
            return ApiResponse.fail("该项目下升降机名称已存在");
        }
        LambdaQueryWrapper<Lift> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(ObjectUtils.isNotEmpty(liftDto.getDeviceCode()),Lift::getDeviceCode,liftDto.getDeviceCode())
                          .eq(Lift::getTyDeleteStatus,0);

        List<Lift> liftList = liftDao.selectList(lambdaQueryWrapper);
        if(liftList.size()>0){
            return ApiResponse.fail("设备编号重复，请重新选择设备！");
        }

        Lift lift = new Lift();
        BeanUtil.copyProperties(liftDto, lift);
        lift.setId(IdUtil.randomUUID());
        //lift.setTyProjectCode(ContextUtil.getSessionUser().getTenantCode());
        lift.setTyCreateTime(new Date());
      //  lift.setTyCreateUserid(ContextUtil.getUserId());
      //  lift.setTyCreateUserName(ContextUtil.getUserName());
        lift.setTyDeleteStatus(0);
        liftDao.insert(lift);

        //保存升降机实时数据
        for(int i = 1; i <= 8; i++){
            LiftData liftData = new LiftData();
            liftData.setId(IdUtil.randomUUID());
            liftData.setLiftId(lift.getId());
            liftData.setLiftName(lift.getLiftName());
            liftData.setDataStatus(0);
            liftData.setDataType(i);
          //  liftData.setMeasureValue(BigDecimal.ZERO);
            liftData.setCollectionTime(new Date());
            liftData.setTyProjectCode(lift.getTyProjectCode());
           // liftData.setTyCreateUserid(ContextUtil.getUserId());
           // liftData.setTyCreateUserName(ContextUtil.getUserName());
            liftData.setTyCreateTime(new Date());
            liftDataDao.insert(liftData);
        }

        return ApiResponse.success();
    }

    @Override
    public ApiResponse updateLift(LiftDto liftDto) {
        Lift liftOld = liftDao.selectById(liftDto.getId());
        //查询升降机是否已存在
        LambdaQueryWrapper<Lift> wrapper = new LambdaQueryWrapper();
        wrapper.eq(ObjectUtils.isNotEmpty(liftDto.getLiftName()),Lift::getLiftName,liftDto.getLiftName())
                .eq(ObjectUtils.isNotEmpty(liftDto.getTyProjectCode()),Lift::getTyProjectCode,liftDto.getTyProjectCode())
                .eq(Lift::getTyDeleteStatus,0);
        Lift lift1 = liftDao.selectOne(wrapper);
        if(ObjectUtils.isNotEmpty(lift1) && !liftOld.getId().equals(lift1.getId())){
            return ApiResponse.fail("该项目下升降机名称已存在");
        }
        if(liftOld != null){
            /*String[] ignoreProperties = {"tyCompanyName", "tyCompanyCode", "tyProjectName", "tyProjectCode", "tyCreateTime",
            "tyCreateUserid", "tyCreateUserName", "tyLastUpdateTime", "tyLastUpdateUserid", "tyLastUpdateUserName",
            "tyDeleteStatus", "tyOpterminal", "tyRemark"};*/
            CopyOptions copyOptions = CopyOptions.create();
            copyOptions.setIgnoreNullValue(true);
            BeanUtil.copyProperties(liftDto, liftOld, copyOptions);
            liftOld.setTyLastUpdateTime(new Date());
           // liftOld.setTyLastUpdateUserid(ContextUtil.getUserId());
           // liftOld.setTyLastUpdateUserName(ContextUtil.getUserName());
            this.saveOrUpdate(liftOld);
        }
        return ApiResponse.success();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ApiResponse deleteById(LiftDto liftDto) {
        Lift liftOld = liftDao.selectById(liftDto.getId());
        if(liftOld != null){
            liftOld.setTyDeleteStatus(1);
            liftOld.setTyLastUpdateTime(new Date());
          //  liftOld.setTyLastUpdateUserid(ContextUtil.getUserId());
          //  liftOld.setTyLastUpdateUserName(ContextUtil.getUserName());

            this.saveOrUpdate(liftOld);
            //删除升降机实时数据
            liftDataDao.deleteLiftDataListByLiftId(liftDto.getId());
        }
        return ApiResponse.success();
    }

    /**
     * 修改通知配置
     * @param liftDto
     * @return
     */
    @Override
    public ApiResponse updateNotice(LiftDto liftDto) {
        Lift liftOld = liftDao.selectById(liftDto.getId());
        if(liftOld != null){
            liftOld.setTyDeleteStatus(1);
            liftOld.setTyLastUpdateTime(new Date());
            //  liftOld.setTyLastUpdateUserid(ContextUtil.getUserId());
            //  liftOld.setTyLastUpdateUserName(ContextUtil.getUserName());
            this.saveOrUpdate(liftOld);
        }
        return ApiResponse.success();
    }
}

